package com.gears.filecover.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.csource.test.FastDFSFile;
import org.csource.test.FileManager;
import org.springframework.stereotype.Service;

import com.gears.core.util.PropertyUtil;
import com.gears.covfile.DocToFdpLibre;
import com.gears.dataSource.DataSource;
import com.gears.entity.Broadcasrtccontent;
import com.gears.ffmpeg.ConvertServlets;
import com.gears.filecover.dao.FindData;

/**
 * 自动运行
 * 
 * @author Administrator
 * @version 2016年8月10日
 */
@Service
@DataSource("myDataSource")
public class FileConverter{

	@Resource
	private FindData findData;
	
	public Logger log = Logger.getLogger(this.getClass());
	
	public  boolean cover(){
		boolean returnFlg = false;
		String location = "";
		
		try{
			Broadcasrtccontent data = new Broadcasrtccontent(); 
			synchronized (this) {
		// 获取第一条数据
			 data = findData.findFirstBroadcasrtccontent();
//			System.out.println(data);
			/*if (data != null) {
				location = data.getLocation().replaceAll("/", "\\");
			} else {
				log.info("not cover data ...");
				return returnFlg;
			}*/
			if(data != null){
				System.out.println();
				location = data.getLocation();
				System.out.println("地址 : " + location);
				System.out.println(data.getId());
				findData.updateStatus(data.getId(), 1);
			}
			}
				
			if(data != null){
				URL urlfile = new URL(location);
				HttpURLConnection urlcon = (HttpURLConnection) urlfile.openConnection();
				//Long TotalSize=Long.parseLong(urlcon.getHeaderField("Conent-Length"));
				if(urlcon.getHeaderField("Content-Length")!=null){
					returnFlg = transferFile(data);
					//System.out.println(urlcon.getHeaderField("Content-Length"));
				}else{
					log.info("文件不存在");
					findData.updateStatus(data.getId(), 8);
					return returnFlg;
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			log.error(e.getClass().getName(),e);
		}
//			File file = new File("D:\testTrans\123.docx");
//			Broadcasrtccontent data = new Broadcasrtccontent();
//			data.setFileType("docx");
//			data.setLocation("D:\\testTrans\\哈哈.docx");
//			returnFlg = transferFile(data);
			return returnFlg;
	}
		
		public boolean transferFile(Broadcasrtccontent data){
			Properties prop = new Properties();
			boolean result = false;
//		// 根据格式进行 - 转换
			try {
				prop.load(this.getClass().getResourceAsStream("/filetype.properties"));
				@SuppressWarnings("rawtypes")
				Enumeration en = prop.propertyNames();
				
				while (en.hasMoreElements()) {
					String key = (String) en.nextElement();
					if ("format_docs".equals(key)) {
						String Property = prop.getProperty(key);
						String[] val = Property.split(",");
						for (int i = 0; i < val.length; i++) {
							System.out.println(val[i]);
							if (data.getFileType().equals(val[i])) {
								if(data.getFileType().equals("pdf")){
									String path = PropertyUtil.getConfigureProperties("fileManage_protocol") + PropertyUtil.getConfigureProperties("internet_ip") + ":"
											+ PropertyUtil.getConfigureProperties("tracker_ngnix_port") + "/" + data.getGroup() + "/" + data.getRemoteName();
									findData.updateStatus(data.getId(), 2);
									findData.updateLocation(data.getId(),path);
								}else{
//								result = docToPdf(data,PropertyUtil.getConfigureProperties("outcover_file_path_pdf"));
								System.out.println(data.getGroup()+data.getRemoteName());
								//byte[] file = FileManager.downloadFile(data.getGroup(), data.getRemoteName());
								File down = new File(PropertyUtil.getConfigureProperties("download_file_path"));
								if(!down.exists()){
									down.mkdirs();
								}
								this.downloadfile(data.getLocation(),PropertyUtil.getConfigureProperties("download_file_path")+ data.getFilename()+"."+data.getFileType() );
								File f = new File(PropertyUtil.getConfigureProperties("download_file_path")+ data.getFilename()+"."+data.getFileType() );
								if(f.exists()){
									data.setLocation(PropertyUtil.getConfigureProperties("download_file_path") + data.getFilename()+"."+data.getFileType() );
									File dir = new File(PropertyUtil.getConfigureProperties("outcover_file_path_pdf"));
									if (!dir.exists() )  
						            {  
						                dir.mkdirs();  
						            }  
									result = docToPdf(data,PropertyUtil.getConfigureProperties("outcover_file_path_pdf"));
								}else{
									System.out.println("下载转换文件失败");
									log.info("下载转换文件失败");
									findData.updateStatus(data.getId(), 0);
								}
								}
							}
						}
					} else if ("format_mvs".equals(key)) {
						String Property = prop.getProperty(key);
						String[] val = Property.split(",");
						for (int i = 0; i < val.length; i++) {
							System.out.println(val[i]);
							if (data.getFileType().equals(val[i])) {
								if(data.getFileType().equals("mp4")){
									String path = PropertyUtil.getConfigureProperties("fileManage_protocol") + PropertyUtil.getConfigureProperties("internet_ip") + ":"
											+ PropertyUtil.getConfigureProperties("tracker_ngnix_port") + "/" + data.getGroup() + "/" + data.getRemoteName();
									findData.updateStatus(data.getId(), 2);
									findData.updateLocation(data.getId(),path);
								}else{
									String filename = UUID.randomUUID().toString().replaceAll("-", "")+".mp4";
									File dir = new File(PropertyUtil.getConfigureProperties("outcover_file_path_media"));
									if (!dir.exists() )  
									{  
										dir.mkdirs();  
									}  
									result = mvToMp4(data, PropertyUtil.getConfigureProperties("outcover_file_path_media")+filename);
								}
								//String filename = location.substring(location.lastIndexOf("/")+1, location.lastIndexOf("."))+".mp4";
							}
						}
					}else{
//						throw new Exception("文件格式不支持转换");
						log.info("文件格式不支持转换");
						findData.updateStatus(data.getId(), 3);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				findData.updateStatus(data.getId(), 0);
				log.error(e.getClass().getName(),e);
			}
		return result;
	}
		
	public  boolean mvToMp4(Broadcasrtccontent data, String outLocation) {
		FileInputStream fis = null;
		boolean resData = false;
		try{
			resData = new ConvertServlets().transfer(data.getLocation(),outLocation, "");
			if (resData) {
				System.out.println(outLocation);
				File file = new File(outLocation);
				if(file.exists()){
					fis = new FileInputStream(file);
				    byte[] file_buff = null;
				    if (fis != null) {
				    	int len = fis.available();
				    	file_buff = new byte[len];
				    	fis.read(file_buff);
				    }
				   String name = UUID.randomUUID().toString().replaceAll("-", "");
				  FastDFSFile fastFile = new FastDFSFile(name, file_buff, "mp4");
				  String fileAbsolutePath = FileManager.upload(fastFile);
				  URL urlfile = new URL(fileAbsolutePath);
			      HttpURLConnection urlcon = (HttpURLConnection) urlfile.openConnection();
			     // System.out.println("哈哈哈哈哈哈啊哈哈："+urlcon.getHeaderField("Content-Length"));
			      if(urlcon.getHeaderField("Content-Length")!=null){
			    	  //System.out.println("message:"+urlcon.getHeaderField("Content-Length"));
			    	  findData.updateLocation(data.getId(),fileAbsolutePath);
						findData.updateStatus(data.getId(), 2);
						
//						returnFlg = true;
			      }else{
			    	  throw new Exception("上传转换文件失败");
			      }
				}else{
					throw new Exception("转换文件不存在");
				}
			} else {
				throw new Exception("转换文件出错");
				//findData.updateStatus(data.getId(), 3);
			}
			return resData;
		}catch (Exception e){
			e.printStackTrace();
			log.error(e.getClass().getName(),e);
			findData.updateStatus(data.getId(), 0);
			resData = false;
			return resData;
		}finally{
			try {
				if(fis != null){
					fis.close();
					File file = new File(outLocation);
					file.delete();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error(e.getClass().getName(),e);
				e.printStackTrace();
			}
		}
		
		
	}

	public  boolean docToPdf(Broadcasrtccontent data, String outLocation) {
		System.out.println("doc pdf method ...");
		boolean returnFlg = false;
		FileInputStream fis = null;
		String inputLocation = data.getLocation();
		String name = inputLocation.substring(inputLocation.lastIndexOf(File.separator)+1,inputLocation.lastIndexOf("."));
		System.out.println(name);
		try {
			System.out.println("开始啦、、、、、");
			String resData = DocToFdpLibre.doDocToFdpLibre(data.getLocation(),
					outLocation);
			System.out.println("结束啦、、、、、");
			//File resFile = new File(resData);

			if (resData.equals("success")) {
				System.out.println("转换成功...");
				//boolean resFlg = findData.updateLocation(data.getId(), resData);
				//findData.updateStatus(data.getId(), 2);
//				File file = new File(outLocation+name+".pdf");
				File file = new File(outLocation+name+".pdf");
				System.out.println(outLocation+name+".pdf");
				if(file.exists()){
					//@SuppressWarnings("resource")
					fis = new FileInputStream(file);
				    byte[] file_buff = null;
				    if (fis != null) {
				    	int len = fis.available();
				    	file_buff = new byte[len];
				    	fis.read(file_buff);
				    }

				  FastDFSFile fastFile = new FastDFSFile(
						  "file", file_buff, file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()));
				  String fileAbsolutePath = FileManager.upload(fastFile);
				  URL urlfile = new URL(fileAbsolutePath);
			      HttpURLConnection urlcon = (HttpURLConnection) urlfile.openConnection();
			      if(urlcon.getHeaderField("Content-Length")!=null){
			    	  findData.updateLocation(
								data.getId(),fileAbsolutePath);
						findData.updateStatus(data.getId(), 2);
			    	  System.out.println(outLocation+name+".pdf");
						
						File file2 = new File(inputLocation);
						file2.delete();
						returnFlg = true;
			      }else{
			    	  throw new Exception("上传转换文件失败");
			      }
					
				}else{
					throw new Exception("转换文件不存在");
				}

			} else {
				// 转换后的文件不是正常的文件...
				throw new Exception("转换文件出错");
				/*findData.updateStatus(data.getId(), 3);
				return returnFlg;*/
			}
			//System.out.println("转换返回 ： " + resData);
			return returnFlg;
		} catch (Exception e){
			log.error(e.getClass().getName(),e);
			findData.updateStatus(data.getId(), 0);
			e.printStackTrace();
			return returnFlg;
		}finally{
			try {
				if(fis != null){
					fis.close();
					File file = new File(outLocation+name+".pdf");
					file.delete();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error(e.getClass().getName(),e);
				e.printStackTrace();
			}
		}
		
	}
	
	public  void downloadfile(String url, String filepath){
		int cache = 10 * 1024;
        try  
        {  
        	@SuppressWarnings("deprecation")
			HttpClient client = new DefaultHttpClient();  
            HttpGet httpget = new HttpGet(url);  
            HttpResponse response = client.execute(httpget);  
  
            HttpEntity entity = response.getEntity();  
            InputStream is = entity.getContent();  
           /* if (filepath == null)  
                filepath = getFilePath(response);  */
            File file = new File(filepath);  
            file.getParentFile().mkdirs();  
            FileOutputStream fileout = new FileOutputStream(file);  
            /** 
             * 根据实际运行效果 设置缓冲区大小 
             */  
            byte[] buffer=new byte[cache];  
            int ch = 0;  
            while ((ch = is.read(buffer)) != -1) {  
                fileout.write(buffer,0,ch);  
            }  
            is.close();  
            fileout.flush();  
            fileout.close();  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
	}

	// @Override
	public void run() {
//		while (true) {
//			boolean flg = false;
//			String outLocation = "D:\\test\\"
//					+ UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
//			try {
//				flg = AutoRuning.cover(outLocation);
//				if (flg == true) {
//					// 根據地址上傳文件返回文件地址.
//					UpLoadFile.upload(outLocation);
//					UpLoadFile.getFile(UpLoadFile.getBytes(outLocation),
//							outLocation.substring(
//									0,
//									outLocation.substring(
//											0,
//											outLocation.substring(
//													0,
//													outLocation
//															.lastIndexOf("."))
//													.length()).length()),
//							outLocation.substring(outLocation.lastIndexOf("."),
//									outLocation.length()));
//				}
//				Thread.sleep(5000);
//			} catch (IOException e) {
//				log.warning(e.getMessage());
//			} catch (Exception e) {
//				log.warning(e.getMessage());
//			} finally {
//				System.out.println("转换是否成功 : " + flg);
//			}
//		}
	}

	public static void main(String[] args) {
//		log4.info("autorun ing ... ");
//		log4.warn("WARN ...");
//		log.info("info level");
		
//		AutoRuning m = new AutoRuning();
//		Thread t = new Thread(m, "A");
//		t.start();
		
	}

}
	
